package com.xxl.job.executor.common.util.http;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @author YTDOLLY
 *
 */

public class HttpClientCommonUtils {
	private final static Log logger = LogFactory.getLog(HttpClientCommonUtils.class);
	

	
	public static HttpResposeModel request(HttpRequestModel requestModel, HttpsInitManager manager) throws Exception {
		CloseableHttpClient httpclient = manager.getHttpsClientByPoolNew();
		HttpPost httppost = null;
		CloseableHttpResponse response = null;
		try {
//			String postUrl =requestModel.getServerUrl()+"/"+requestModel.getFilename().replace(".", "@_@");
			logger.info("请求url:"+requestModel.getServerUrl());
			httppost = new HttpPost(requestModel.getServerUrl());
			// 设置请求Header
			setPostHead(httppost, requestModel.getHeadMap());
//			//流的方式
//			ContentBody contentBody = new ByteArrayBody(requestModel.getData(), requestModel.getFilename());

			StringBody imageId = new StringBody(requestModel.getImageId(), ContentType.create(
					"text/plain", Consts.UTF_8));
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			multipartEntityBuilder.setBoundary("inputstream");
			multipartEntityBuilder.addPart("binFile", imageId);

			HttpEntity reqEntity = multipartEntityBuilder.build();
			httppost.setEntity(reqEntity);

			response = httpclient.execute(httppost);
			// 处理请求的返回
			try {
				return response(response);
			} finally {
				response.close();
			}
		} catch(IOException e) {
			logger.info("请求IO错误，", e);
			throw e;
		} catch (Exception e) {
			logger.info("--请求报错！--", e);
			throw new Exception("--请求报错！--");
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					logger.error("读取https响应关闭response出错！", e);
				}
			}
		}
	}

	/**
	 * 处理返回响应
	 * @param response
	 * @return
	 */
	private static HttpResposeModel response( CloseableHttpResponse response) throws Exception {
		HttpResposeModel resposeModel = new HttpResposeModel();
		ByteArrayOutputStream swapStream = null;
		InputStream is = null;
		try {
			// 获取返回的所有Header数据
			Header[] headers = response.getAllHeaders();
			 Map<String, String> headMap=getMapByHeaders(headers);
			resposeModel.setHeadMap(headMap);

			// 返回响应的状态
			int statusCode = response.getStatusLine().getStatusCode();
			resposeModel.setStatusCode(statusCode);
			// 获取返回的Content
			HttpEntity httpEntity = response.getEntity();
			
			if (statusCode == HttpStatus.SC_OK) {// 返回处理成功
				logger.info("--响应成功，状态码200！--");
			}else {
				logger.error("---响应失败，状态码"+statusCode+"！--");
			}
			is = httpEntity.getContent();
			swapStream = new ByteArrayOutputStream();
	        byte[] buff = new byte[100];  
	        int rc = 0;  
	        while ((rc = is.read(buff, 0, 100)) > 0) {  
	            swapStream.write(buff, 0, rc);  
	        }  
	        byte[] in2b = swapStream.toByteArray(); 
	        resposeModel.setData(in2b);
			//文件名
//			String fileName=headMap.get("Content-Disposition");
//			int beginIndex = fileName.indexOf("=");
//			fileName=fileName.substring(beginIndex+1);
//            resposeModel.setFileName(fileName);
			EntityUtils.consume(httpEntity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("---响应返回时报错！--",e);
			throw new Exception("---响应返回时报错！--");
		}finally {
			if(swapStream!=null)swapStream.close();
			if(is!=null)is.close();
		}
		return resposeModel;
	}

	/**
	 * 获取响应的Header 全部内容
	 * 
	 * @param headers
	 * @return
	 */
	private static Map<String, String> getMapByHeaders(Header[] headers) {
		Map<String, String> headMap = null;
		if (headers != null && headers.length > 0) {
			headMap = new HashMap<>();
			for (int i = 0; i < headers.length; i++) {
				Header header = headers[i];
				headMap.put(header.getName(), header.getValue());
			}
		}
		return headMap;
	}
	
	/**
	 * 设置http的HEAD
	 * 
	 * @param httpPost
	 * @param headMap
	 */
	private static void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
		if (headMap != null && headMap.size() > 0) {
			Set<String> keySet = headMap.keySet();
			for (String key : keySet) {
				httpPost.addHeader(key, headMap.get(key));
			}
		}
	}
}
